package com.pay.buffer;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zhouyihe
 * @ClassName LogBuffer
 */
@Slf4j
@Component
public class LogBuffer {
    public LogBuffer() {
        //利用单例线程池 启动线程
        Executors.newSingleThreadExecutor()
                .execute(new LogTaskThread());
    }

    /**
     * 手写出异步高性能日志框架 吊打面试官
     * 内存存中暂时缓存日志
     */
    private static LinkedBlockingQueue<String> logs =
            new LinkedBlockingQueue<String>();

    public static void info(String log) {
        // 1.将日志暂时缓存在我们的 并发队列中
        logs.offer(log);
    }

    /**
     * 标记一直循环
     */
    private volatile boolean isRun = true;
    public static final Integer BUFFER_SIZE = 5;
    public static final Long BUFFER_INTERVAL_TIME = 20l;

    /**
     * 刷盘线程  从队列中取出 日志写入到磁盘中
     * 一直在运行状态
     */
    class LogTaskThread implements Runnable {
        @Override
        public void run() {
            //改成批量从队列中取出很多日志 写入磁盘中
            while (isRun) { // 代码优化避免cpu飙高
                // 2.刷盘的线程从队列中取出日志
//                List<String> tempBuffer =
//                        new ArrayList<>(BUFFER_SIZE);
                try {
                    StringBuffer sf = new StringBuffer();
                    for (int i = 0; i < BUFFER_SIZE; i++) {
                        // 为了避免cpu飙高的问题
                        String log = logs.poll(BUFFER_INTERVAL_TIME
                                , TimeUnit.MILLISECONDS);
                        // 追加日志
                        if (!StringUtils.isEmpty(log)) {
                            sf.append(log + "/n");
                            ;
                        }
                    }
                    // 批量抓取5条日志
                    String log = sf.toString();
                    if (!StringUtils.isEmpty(log)) {
                        // 刷盘磁盘中
                        FileUtil.appendString(log, "D:\\log\\mayikt.log", "UTF-8");
                    }
                } catch (Exception e) {
                    log.error("e:{}", e);
                }
            }
        }


    }

    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingDeque<String> linkedBlockingDeque =
                new LinkedBlockingDeque<String>();
        linkedBlockingDeque.offer("mayikt1");
        linkedBlockingDeque.offer("mayikt2");
        System.out.println(linkedBlockingDeque.poll());
        System.out.println(linkedBlockingDeque.poll());
        System.out.println(linkedBlockingDeque.poll(3, TimeUnit.SECONDS));
        System.out.println("meite666");
    }
}
